package com.enthusiasm.constants;

import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.media.SoundPool;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/**
 * 
 *
 */
public abstract class AbstractSurfaceView extends SurfaceView implements SurfaceHolder.Callback,Runnable{

	private SurfaceHolder sfh;
	private Thread th;
	private boolean flag;
	public  int screenW, screenH;
	public Paint paint;
	public Canvas canvas;
	public Context context;
	public boolean isMediaStop;
	public boolean isSoundStop;
	public SoundPool soundPool;
	public Intent service;
	private boolean isInitOk = false;
	/**
	 * SurfaceView��ʼ������
	 */
	public AbstractSurfaceView(Context context) {
		super(context);
		this.context = context;
		sfh = this.getHolder();
		sfh.addCallback(this);
		setFocusable(true);
		setFocusableInTouchMode(true);
		setKeepScreenOn(true);
		paint = new Paint();
		paint.setAntiAlias(true);
		paint.setFilterBitmap(true);
		this.isMediaStop = SoundManager.getInstance(context).getIsMediaStop();
		this.isSoundStop = SoundManager.getInstance(context).getIsSoundStop();
		init();
	}
	
	public void myDraw() {
		try {
			canvas = sfh.lockCanvas();
			if (canvas != null) {
				canvas.drawARGB(0,0, 0, 0);
				draw();
			}
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			if (canvas != null)
				sfh.unlockCanvasAndPost(canvas);
		}
	}

	public abstract void draw();

	public abstract void logic();
	
	public void run() {
		while (flag) {
			long start = System.currentTimeMillis();
			if(isInitOk){
				myDraw();
				logic();
			}
			long end = System.currentTimeMillis();
			try {
				if (end - start < 50) {
					Thread.sleep(50 - (end - start));
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}		
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		screenW = width;
		screenH  = height;
		initRect();
		isInitOk = true;
	}

	public void surfaceCreated(SurfaceHolder holder) {
		flag = true;
		th = new Thread(this);
		th.start();
	}

	private void init() {
		initBitmap();
	}

	public abstract void initBitmap();
	public abstract void initRect();
	
	public void surfaceDestroyed(SurfaceHolder holder) {
		flag = false;		
	}

	public abstract void releaseBitmap();
}